package cn.dansj.utils.project;

import cn.dansj.annotation.InterfaceParam;
import cn.dansj.annotation.MarkAsApi;
import cn.dansj.annotation.MarkAsTask;
import cn.dansj.common.utils.json.DictMap;
import cn.dansj.common.jdbc.DBUtils;
import cn.dansj.common.springboot.reflect.ScanPackageClass;
import cn.dansj.common.utils.transfer.GetTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;

import java.io.File;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

public class SyncTaskAndInterfaceToDataBase {
    private static final String ANSI_RESET = "\u001B[0m";
    private static final String ANSI_RED = "\u001B[31m";
    private static final String ANSI_GREEN = "\u001B[32m";
    private static final String ANSI_YELLOW = "\u001B[33m";
    private static final Logger logger = LoggerFactory.getLogger(SyncTaskAndInterfaceToDataBase.class);

    public static void main(String[] args) {
        Properties prop = new Properties();
        ClassLoader classLoader = SyncTaskAndInterfaceToDataBase.class.getClassLoader();
        try (InputStream input = classLoader.getResourceAsStream("application-dev.properties")) {
            if (input == null) {
                System.out.println("Sorry, unable to find bootstrap.yml");
                return;
            }
            // 加载配置文件
            prop.load(input);
            // 获取配置项
            String url = prop.getProperty("spring.datasource.druid.url");
            String username = prop.getProperty("spring.datasource.druid.username");
            String password = prop.getProperty("spring.datasource.druid.password");
            final JdbcTemplate jdbcTemplate = DBUtils.createJdbcTemplate(url, username, password);

            final Set<String> apiPackages = ScanPackageClass.builder().addPackage("cn.dansj.handler.interfaces").setFilterClass(MarkAsApi.class).build();
            for (String packageName : apiPackages) {
                final Class<?> aClass = Class.forName(packageName, false, classLoader);
                final URL resource = aClass.getResource("");
                if (resource == null) continue;
                final String interfaceName = aClass.getSimpleName().substring(0, 1).toLowerCase() + aClass.getSimpleName().substring(1);
                String path = resource.getPath().replace("/target/classes/", "/src/main/java/") + aClass.getSimpleName() + ".java";
                String sourceCode = String.join("\n", Files.readAllLines(Paths.get(new File(path).getPath()), StandardCharsets.UTF_8));
                final Method execute = aClass.getMethod("execute", Map.class);
                final InterfaceParam[] annotations = execute.getAnnotationsByType(InterfaceParam.class);
                DictMap dictMap = DictMap.of();
                for (InterfaceParam param : annotations) {
                    dictMap.put(param.value(), DictMap.of("name", param.value(), "require", param.require() ? 1 : 2, "content", param.comment(), "default", param.defaultValue()));
                }
                final int update = jdbcTemplate.update("update x_interface_info set params=?,code=?,update_time=? where interface_name=? and type='java'", dictMap.toJSONString(), sourceCode, GetTime.dbTimestamp(), interfaceName);
                if (update == 0) {
                    logger.info(ANSI_YELLOW + "{}接口 [{}] 没有对应存在的记录,更新失败" + ANSI_RESET, aClass.getName(), interfaceName);
                } else if (update == 1) {
                    logger.info(ANSI_GREEN + "{}接口 [{}] 信息更新成功" + ANSI_RESET, aClass.getName(), interfaceName);
                } else {
                    logger.info(ANSI_RED + "{}接口 [{}] 信息更新异常" + ANSI_RESET, aClass.getName(), interfaceName);
                }
            }

            final Set<String> taskPackages = ScanPackageClass.builder().addPackage("cn.dansj.handler.tasks").setFilterClass(MarkAsTask.class).build();
            for (String packageName : taskPackages) {
                final Class<?> aClass = Class.forName(packageName, false, classLoader);
                final URL resource = aClass.getResource("");
                final MarkAsTask markAsTask = aClass.getAnnotation(MarkAsTask.class);
                if (markAsTask.id() < 0 || resource == null) continue;
                final String taskName = aClass.getSimpleName().substring(0, 1).toLowerCase() + aClass.getSimpleName().substring(1);
                String path = resource.getPath().replace("/target/classes/", "/src/main/java/") + aClass.getSimpleName() + ".java";
                String sourceCode = String.join("\n", Files.readAllLines(Paths.get(new File(path).getPath()), StandardCharsets.UTF_8));
                final int update = jdbcTemplate.update("update xxl_job_info set glue_source = ?,update_time=? where id=?", sourceCode, GetTime.dbTimestamp(), markAsTask.id());

                if (update == 0) {
                    logger.info(ANSI_YELLOW + "{}task任务 [{}] 没有对应存在的记录,更新失败" + ANSI_RESET, aClass.getName(), markAsTask.id());
                } else if (update == 1) {
                    logger.info(ANSI_GREEN + "{}task任务 [{}] 信息更新成功" + ANSI_RESET, aClass.getName(), markAsTask.id());
                } else {
                    logger.info(ANSI_RED + "{}task任务 [{}] 信息更新异常" + ANSI_RESET, aClass.getName(), markAsTask.id());
                }
            }
        } catch (Exception ex) {
            System.out.println("Error: " + ex.getMessage());
        }
    }
}